package xhwl.insurance.upgrade;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.RemoteViews;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;

import de.greenrobot.event.EventBus;
import xhwl.insurance.R;
import xhwl.insurance.util.XHLog;


/**
* 升级模块下载安装包服务
* @author lim
* @date 2017年2月9日
* @version 1.0
*/
public class UpgradeService extends Service {
    public static final String EXTRA_FILE_URL="file_url";
    public static final String EXTRA_VERSION_CODE="version_code";
    public static final String EXTRA_VERSION_NAME="version_name";
    private boolean isDownloading = false;
    private HttpHandler<File> handler;
    UpgradeDao dao;
    Upgrade upgrade;

    String filePath; //下载文件绝对路径(包括文件名)

    Context context;
    NotificationManager manager;
    Notification notify = new Notification();

    @Override
    public void onCreate() {
        super.onCreate();
        XHLog.e("onCreate()");
        context=this;
        manager = (NotificationManager) context
                .getSystemService((context.NOTIFICATION_SERVICE));
        notify.icon = R.drawable.appicon;
        // 通知栏显示所用到的布局文件
        notify.contentView = new RemoteViews(context.getPackageName(),
                R.layout.notify_view);
        manager.notify(100, notify);

        dao=new UpgradeDao(this);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String fileUrl=intent.getStringExtra(EXTRA_FILE_URL);
        String versionCode=intent.getStringExtra(EXTRA_VERSION_CODE);
        String versionName=intent.getStringExtra(EXTRA_VERSION_NAME);
        XHLog.e("onStartCommand()--downUrl="+fileUrl+" verCode="+versionCode+" verName="+versionName);
        download(fileUrl,versionCode,versionName);

        return START_REDELIVER_INTENT;
    }
    /**
     * 更新通知栏
     */
    private Handler completeHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if(msg.what==-1){
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, "下载失败");
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);// 清除通知栏
                manager.cancel(100);
            }
            else if (msg.what < 100) {
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, msg.what + "%");
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);
                manager.notify(100, notify);
            } else {
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, "下载完成");
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);// 清除通知栏
                manager.cancel(100);
            }
        };
    };
    /**
     * 利用xUtils进行断点续传下载
     */
    private void download(String fileUrl, final String versionCode, final String versionName) {
        HttpUtils httpUtils = new HttpUtils();
        if (!isDownloading) {
            isDownloading = true;
            //第一个参数:下载地址
            //第二个参数:文件存储路径
            //第三个参数:是否断点续传
            //第四个参数:是否重命名
            //第五个参数:请求回调

            final String saveFileName=fileUrl.substring(fileUrl.lastIndexOf("/")+1);
            upgrade=dao.find(versionCode);
            upgrade.setVersion_name(versionName);
            upgrade.setVersion_code(versionCode);
            upgrade.setSave_path(saveFileName);
            filePath=UpgradeMgr.apkSavePath+ File.separator+saveFileName;
            handler = httpUtils.download(fileUrl, filePath, true, false, new RequestCallBack<File>() {
                @Override
                public void onStart() {
                    super.onStart();
                    XHLog.e("开始下载...");

                    upgrade.setCreate_time(System.currentTimeMillis());
                    upgrade.setDownload_state(UpgradeEvent.STATE_START);
                    try {
                        dao.saveOrUpdate(upgrade);
                    } catch (DbException e1) {
                        e1.printStackTrace();
                    }
                    EventBus.getDefault().post(new UpgradeEvent(UpgradeEvent.STATE_START));


                }

                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    XHLog.e(current + "/" + total);
                    int percent=(int)(current*1.0/total*100);
                    XHLog.e("percent=" + percent);
                    completeHandler.sendEmptyMessage(percent);
                }

                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    XHLog.e("下载完成-->" + responseInfo.result.getPath());

                    upgrade.setUpdate_time(System.currentTimeMillis());
                    upgrade.setDownload_state(UpgradeEvent.STATE_COMPLETE);
                    try {
                        dao.saveOrUpdate(upgrade);
                    } catch (DbException e1) {
                        e1.printStackTrace();
                    }
                    isDownloading=false;
                    EventBus.getDefault().post(new UpgradeEvent(UpgradeEvent.STATE_COMPLETE));
                    onDownloadSuccess();
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    XHLog.e("下载失败-->" + s);
                    if("maybe the file has downloaded completely".equals(s)){
                        upgrade.setDownload_state(UpgradeEvent.STATE_COMPLETE);
                    }
                    else{
                        upgrade.setDownload_state(UpgradeEvent.STATE_FAILED);
                    }
                    upgrade.setUpdate_time(System.currentTimeMillis());
                    upgrade.setComment(s);
                    try {
                        dao.saveOrUpdate(upgrade);
                    } catch (DbException e1) {
                        e1.printStackTrace();
                    }
                    isDownloading=false;
                    if(UpgradeEvent.STATE_COMPLETE== upgrade.getDownload_state()){
                        //針對已下載的情況
                        EventBus.getDefault().post(new UpgradeEvent(UpgradeEvent.STATE_COMPLETE));
                        onDownloadSuccess();
                    }
                    else
                    {
                        completeHandler.sendEmptyMessage(-1);
                    }
                }
            });
        }
        else{
            EventBus.getDefault().post(new UpgradeEvent(UpgradeEvent.STATE_DOWNLOADING));
        }
    }
    private void onDownloadSuccess(){
//    	//点击安装PendingIntent  
//        Uri uri = Uri.fromFile(new File(filePath));  
//        Intent installIntent = new Intent(Intent.ACTION_VIEW);  
//        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");                       
//        updatePendingIntent = PendingIntent.getActivity(this, 0, installIntent, 0);  
//        myNotification.changeContentIntent(updatePendingIntent);  
////        myNotification.notification.defaults=Notification.DEFAULT_SOUND;//铃声提醒                      
//        myNotification.changeNotificationText("下载完成，请点击安装！"); 
        stopSelf();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XHLog.e("onDestroy()");
        isDownloading = false;
        if(handler!=null){
            handler.cancel();
        }
    }
}
